package com.my.study.tx;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

/**
 * 声明式事务
 * 
 * 一、环境搭建
 * 1、导入相关依赖
 *  数据源、数据库驱动、spring-jdbc、spring-tx、spring-orm等
 *  
 * 2、配置数据源、JdbcTemplate 
 * 
 * 3、给方法上标注@Transactional，表示当前方法是一个事务方法
 * 
 * 4、@EnableTransactionManagement 开启基于注解的事务管理功能
 * 
 * 5、配置事务管理器来管理事务
 * 
 * @author Carlos
 * @version 1.0.0
 * @date 2022/11/8 22:03
 */
@EnableTransactionManagement
@ComponentScan("com.my.study.tx")
@Configuration
public class TxConfig {
    
    
    @Bean(name = "dataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        
        dataSource.setUsername("root");
        dataSource.setPassword("ydjws");
        dataSource.setUrl("jdbc:mysql://47.98.50.37:3307/my_security?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        
        return dataSource;
    } 
    
    
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }
    
    
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        
        transactionManager.setDataSource(dataSource());
            
        return transactionManager;
    }
    
    @Bean("transactionTemplate")
    public TransactionTemplate transactionTemplate() {
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager());
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        return transactionTemplate;
    }
    
}
